package com.zzw.jwt;

import com.zzw.common.exception.CommonException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.KeyPair;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @author Administrator
 */
public class DefaultJwtService implements JwtService {

    private static final Logger logger = LoggerFactory.getLogger(DefaultJwtService.class);

    private final JwtProperties jwtProperties;
    private final KeyPair key;
    private final SignatureAlgorithm signatureAlgorithm = Jwts.SIG.RS512;

    public DefaultJwtService(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
        this.key = signatureAlgorithm.keyPair().build();
    }

    @Override
    public String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .subject(jwtProperties.getSubject())
                .id(UUID.randomUUID().toString())
                .claims(claims)
                .signWith(key.getPrivate(), signatureAlgorithm)
                .expiration(new Date(System.currentTimeMillis() + jwtProperties.getExpiration()))
                .compact();
    }

    @Override
    public Claims validateToken(String token) {
        try {
            return Jwts.parser().verifyWith(key.getPublic()).build().parseSignedClaims(token).getPayload();
        } catch (Exception e) {
            logger.error("jwt valid error", e);
            throw new CommonException("-10", "jwt valid error");
        }
    }
}
